package io.github.wanggit.antrpc.gateway.web.vo;

import io.github.wanggit.antrpc.gateway.constants.ResultConstants;
import io.github.wanggit.antrpc.gateway.web.utils.CheckSumUtil;
import lombok.Data;

import java.io.Serializable;

@Data
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 6617354242998178674L;
    private int code = ResultConstants.SUCCESS;

    private String msg;

    private T data;

    private String checksum;

    public static <T> Result<T> ok() {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.SUCCESS);
        result.setMsg(ResultConstants.SUCCESS_MSG);
        result.generateCheckSum();
        return result;
    }

    public static <T> Result<T> ok(T data) {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.SUCCESS);
        result.setMsg(ResultConstants.SUCCESS_MSG);
        result.setData(data);
        result.generateCheckSum();
        return result;
    }

    public static <T> Result<T> error() {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.ERROR);
        result.setMsg(ResultConstants.ERROR_MSG);
        result.generateCheckSum();
        return result;
    }

    public static <T> Result<T> error(String errorMessage) {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.ERROR);
        result.setMsg(errorMessage);
        result.generateCheckSum();
        return result;
    }

    public static <T> Result<T> e404() {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.ERROR_404);
        result.setMsg(ResultConstants.ERROR_MSG_404);
        result.generateCheckSum();
        return result;
    }

    public static <T> Result<T> unauth(String message) {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.UNAUTH);
        result.setMsg(null == message ? ResultConstants.UNAUTH_MSG : message);
        result.generateCheckSum();
        return result;
    }

    public static <T> Result<T> unauth() {
        Result<T> result = new Result<>();
        result.setCode(ResultConstants.UNAUTH);
        result.setMsg(ResultConstants.UNAUTH_MSG);
        result.generateCheckSum();
        return result;
    }

    private void generateCheckSum() {
        this.checksum = CheckSumUtil.checksum(this);
    }
}
